package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.behavior.mapper.ApLikesBehaviorMapper;
import com.usian.behavior.service.ApBehaviorEntryService;
import com.usian.behavior.service.ApLikeBehaviorService;
import com.usian.model.behavior.dtos.LikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApLikesBehavior;
import com.usian.model.common.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl extends BaseServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikeBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;//行为实体服务

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1.参数校验
        if (dto == null || dto.getArticleId() == null || dto.getType()<0 || dto.getType()>2 || (dto.getOperation() !=0 && dto.getOperation() != 1))return paramError;
        //2.从AppThreadLocal中拿到用户Id
        Integer userId = AppThreadLocalUtils.getUser().getId();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, null);
        if (apBehaviorEntry == null) return paramDataExist;
        //查询点赞行为      具体行为表的entryId是行为总表的Id
        ApLikesBehavior likesBehavior = getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getArticleId, dto.getArticleId()).eq(ApLikesBehavior::getEntryId, apBehaviorEntry.getId()));
        if (likesBehavior == null && dto.getOperation() == 0 ){//以前没点过赞  现在要点赞
            likesBehavior = new ApLikesBehavior();
            likesBehavior.setOperation(dto.getOperation());
            likesBehavior.setArticleId(dto.getArticleId());
            likesBehavior.setEntryId(apBehaviorEntry.getId());
            likesBehavior.setType(dto.getType());
            likesBehavior.setCreatedTime(new Date());
            save(likesBehavior);
        }else {//以前点过赞，现在根据传入的dto.getOperation()决定是再次赞，还是取消点赞
            if (likesBehavior != null){
                likesBehavior.setOperation(dto.getOperation());
                updateById(likesBehavior);
            }
        }
        return okResult;
    }

    @Override
    public ApLikesBehavior getLikeBehavior(Long articleId, Integer entryId, Integer type) {
        if (articleId == null || entryId == null || type == null){
            System.out.println("参数缺少");
            return null;
        }
        return getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getArticleId,articleId).eq(ApLikesBehavior::getEntryId,entryId).eq(ApLikesBehavior::getType,type));
    }
}
















